package com.sunlee.admin.api.module.oss.cloud;

import cn.hutool.extra.spring.SpringUtil;
import com.sunlee.admin.api.module.oss.cloud.impl.ALiYunCloudStorageService;
import com.sunlee.admin.api.module.oss.cloud.impl.QCloudCloudStorageService;
import com.sunlee.admin.api.module.oss.cloud.impl.QiNiuCloudStorageService;
import com.sunlee.admin.api.module.sys.service.SysParamsService;
import com.sunlee.common.core.constant.Constant;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

/**
 * 文件上传Factory
 *
 * @author sunlee
 */
@Slf4j
public class OssFactory {

    private static final SysParamsService sysParamsService;
    private static AbstractCloudStorageService cloudStorageService;

    public static AbstractCloudStorageService client() {
        return cloudStorageService;
    }

    static {
        sysParamsService = SpringUtil.getBean(SysParamsService.class);
        cloudStorageService = initClient();
    }

    private OssFactory() {
    }

    /**
     * 初始化Oss客户端
     */
    public static AbstractCloudStorageService initClient() {
        //获取云存储配置信息
        CloudStorageConfig config = sysParamsService.getValueObject(Constant.CLOUD_STORAGE_CONFIG_KEY, CloudStorageConfig.class);
        if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
            return registerClient(ALiYunCloudStorageService.class, config);
        }
        else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
            return registerClient(QCloudCloudStorageService.class, config);
        }
        else if (config.getType() == Constant.CloudService.QINIU.getValue()) {
            return registerClient(QiNiuCloudStorageService.class, config);
        }
        else {
            throw new BusinessException(ErrorCodeEnum.STORAGE_INFO_NOT_CONFIG);
        }
    }

    /**
     * 通过反射，实例化具体实现类
     */
    public static <T extends AbstractCloudStorageService> T registerClient(Class<T> clazz, CloudStorageConfig config) {
        try {
            T ossBean = clazz.getConstructor(CloudStorageConfig.class).newInstance(config);
            if (ossBean.ossClient == null) {
                log.warn("OSS客户端未实例化");
                return ossBean;
            }
            log.info("OSS客户端注册成功[{}]", ossBean.getClass().getName());
            return ossBean;
        } catch (Exception ne) {
            throw new BusinessException("OSS客户端注册失败");
        }
    }

    /**
     * 重新初始化
     */
    public static void updateClient() {
        cloudStorageService = initClient();
    }
}